/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package unc.pds.news;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 *
 * @author ain
 */
public class NewsReader {

    public ArrayList getNewsFor(Long contextKey) throws RemoteException {
        ArrayList answer = new ArrayList();
        Connection conn = null;
        Statement state = null;
        ResultSet ans = null;
        try {
            conn = getConnection();
            state = conn.createStatement();
            DateFormat df = new SimpleDateFormat("DD.MM.yyyy hh:mm:ssa");
            ans = state.executeQuery("SELECT "
                    + "ENTITY_ID,"
                    + "EVENT,"
                    + "TO_CHAR(ATIME,'DD.MM.YYYY HH:MI:SSam') chartime "
                    + "FROM NEWS "
                    + "WHERE CONTEXT_ID=" + contextKey
                    + " ORDER BY ATIME DESC");
            while (ans.next()) {
                News temp = new News();
                temp.context = contextKey;
                temp.entityID = new Long(ans.getLong("ENTITY_ID"));
                temp.event = ans.getString("EVENT");
                temp.time = df.parse(ans.getString("chartime"));
                answer.add(temp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ans!=null){
                    ans.close();
                }
                if (state != null) {
                    state.close();
                }
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        return answer;
    }

    private Connection getConnection() throws NamingException, SQLException {
        DataSource ds = (DataSource) (new InitialContext()).lookup("oracle/SOS");
        return ds.getConnection();
    }
}
